home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C/C++ Users Group Library 1996 July
/
C-C++ Users Group Library July 1996.iso
/
listings
/
v_09_07
/
9n07113a
< prev
next >
Wrap
Text File
|
1991-05-26
|
2KB
|
110 lines
/*
*
* Program to illustrate use of typecasting with 'sort' and
* 'search' functions.
*
* Compiled, linked & executed with both Turbo C++ 1.01
* and Turbo C2.01.
*
* Sergio Cherskov 03/26/91
*/
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
/* just to stay generic in description */
#define ANY_LENGTH 34
#define ANY_SIZE 33
/* this solves qsort typecasting problem */
typedef int (*_QSORT_CMP_)(const void *, const void *);
typedef struct {
int len;
int ID;
int year;
char data[ANY_LENGTH];
} DATA;
#define NELEM(array) (sizeof(array)/sizeof(array[0]))
DATA data_array[ANY_SIZE];
void main(void);
int usr_fn1(DATA *D1, DATA *D2);
int usr_fn2(int *key, DATA *D);
int usr_fn3(int *key, DATA *D, int reserved, DATA*unused);
void main(void)
{
int i;
int ID;
DATA *D;
è for ( i=0; i < NELEM(data_array) ; i++ )
{
data_array[i].ID = NELEM(data_array) -i;
data_array[i].len = sizeof(DATA);
}
qsort(&data_array[0], NELEM(data_array),
sizeof(DATA), (_QSORT_CMP_) usr_fn1 );
printf("\nSearching with bsearch\n");
/* Pick an item to search */
ID = NELEM(data_array) / 3;
D = bsearch(&ID, &data_array[0], NELEM(data_array),
sizeof(DATA), (_QSORT_CMP_) usr_fn2 );
printf("Element with ID #%d, %sfound in the array.\n",
ID, D ? "" : "NOT ");
/* check here with sequential search */
printf("Searching with straight search\n");
D = NULL;
for ( i=0; i < NELEM(data_array) ; i++ )
{
if ( data_array[i].ID == ID )
{
D = &data_array[i];
break;
}
}
printf("Element with ID #%d, %sfound in the array.\n",
ID, D ? "" : "NOT ", i);
}
int usr_fn1(DATA *D1, DATA *D2)
{
return ( D1->ID - D2->ID );
}
int usr_fn2(int *key, DATA *D)
{
return ( *key - D->ID );
}
int usr_fn3(int*key, DATA *D, int reserved, DATA *unused)
{
int i;
/*
* The following statements just fool the comiler,
* and prevent warning that 'reserved' and 'unused'
* parameters were not used in function 'usr_fn3'.
*/
i = unused->ID;
i = reserved;
i++;
return ( *key - D->ID );
}